package moe.hotk.repository

import moe.hotk.entity._

import scala.concurrent.stm._

object Truths {

  private val truths = Ref(Seq[Truth]())

  private val idGenerator = new IdGenerator

  def getAll: Seq[Truth] = truths.single()

  def getOneById(id: Long): Option[Truth] = getAll find (_.id == id)

  def create(truth: Truth): Unit = atomic { implicit txn =>
    truths() = (truth copy (id = idGenerator.next())) +: truths()
  }

  def update(truth: Truth): Unit =
    truths.single transform (_ map (t => if (t.id != truth.id) t else truth))

  def delete(id: Long): Unit =
    truths.single transform (_ filter (_.id != id))

}
